//
//  JJOAuthViewController.swift
//  微博1
//
//  Created by 卷卷 on 15/9/2.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import SVProgressHUD

//OAuth授权控制器
class JJOAuthViewController: UIViewController ,UIWebViewDelegate{

    private lazy var webView = UIWebView()
    
    override func loadView() {
        //根视图就是 webView
        view = webView
        webView.delegate = self
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: " 关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充用户信息
    @objc private func autoFill(){
        
        let js = "document.getElementById('userId').value = '15922858700';" +
        "document.getElementById('passwd').value = 'juanjaun2018';"
        
        //执行 js 脚本
        webView.stringByEvaluatingJavaScriptFromString(js)

    }
    
    // 尽量不要让控制器管太多的事
    override func viewDidLoad() {
        webView.loadRequest(NSURLRequest(URL: JJNetwokingTools.shareTools.oauthUrl))
    }
    
    //MARK: - UIWebViewDelegate
    //通常在 IOS 开发中，如果代理方法有 Bool 类型的返回值，返回 true 通常是一切正常
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        let urlString = request.URL!.absoluteString
    //1.判断 request.url 的前半部分是否是回调地址，如果不是回调地址，继续加载
        if !urlString.hasPrefix(JJNetwokingTools.shareTools.redirectUri){
        
            //继续加载
            return true
        }
        
        print(request.URL!.query)
    
    //2.如果是毁掉地址，检查query，查询字符串，判断是否包含 “code＝”
    //query 就是 URL 中‘?’ 后面的所有内容
        if let query = request.URL!.query where query.hasPrefix("code="){
    
    //3.如果有，获取 code
    let code = query.substringFromIndex("code=".endIndex)
    print(code)
            
    //4.调用网络方法，获取token
    JJNetwokingTools.shareTools.loadAccessToken(code).subscribeNext({ (result) -> Void in
       
        print(result)
       
        }, error: { (error) -> Void in
        
            print(error)

    })
            
        }else{
            print("取消")
        }
    return false
}
//    private func loadUserInfo(account: JJUserAccount){
//        
//    JJNetwokingTools.shareTools.loadUserInfo(account.uid!, access_token: account.access_token!).subscribeNext({ (result) -> Void in
//        
//        let dict = result as! [String :AnyObject]
//        
//        //设置帐号属性
//        account.name = dict["name"] as? String
//        account.avatar_large = dict["avatar_large"] as? String
//        
//        print(account)
//        
//        //保存账号
//        account.saveUserAccount()
//
//        
//    } ,error:{ (error) -> Void in
//            
//            printLog(error)
//            
//        }) {() -> Void in
//            
//        }
//    }
    
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
}
